package com.bensoft.minesweeper.gui.minesweeperframe.displaypanel;

import com.bensoft.minesweeper.resources.FileResources;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

/**
 * Display a three digit seven-segment display. It can display numbers between
 * 999 and -99, inclusive.
 *
 * @author Ben Wolsieffer
 */
public class Display3Digit extends JPanel {

    volatile int number;
    Image firstImage, secondImage, thirdImage;
    private final Object imageLock = new Object();

    public Display3Digit(int n) {
        setPreferredSize(new Dimension(39, 23));
        setNumber(n);
        FileResources.addThemeChangeListener(new FileResources.ThemeChangeListener() {
            @Override
            public void themeChanged() {
                setNumber(number);
            }
        });
    }

    public Display3Digit() {
        this(0);
    }

    @Override
    public void paint(Graphics g) {
        synchronized (imageLock) {
            g.drawImage(firstImage, 0, 0, this);
            g.drawImage(secondImage, 13, 0, this);
            g.drawImage(thirdImage, 26, 0, this);
        }
    }

    public final void setNumber(int n) {
        number = n;

        if (n < -99 || n > 999) {
            return;
        }
        synchronized (imageLock) {
            thirdImage = FileResources.getDigitImage(Math.abs(n % 10));
            n /= 10;
            secondImage = FileResources.getDigitImage(Math.abs(n % 10));
            n /= 10;
            if (n >= 0) {
                firstImage = FileResources.getDigitImage(Math.abs(n % 10));
            } else {
                firstImage = FileResources.getNegDigitImage();
            }
        }
        repaint();
    }

    public int getNumber() {
        return number;
    }
}
